package cn.cdu.medical.controller;

import cn.cdu.medical.service.IDoctorWorkbenchService;
import cn.cdu.basics.baseVo.Result;
import cn.cdu.basics.utils.ResultUtil;
import cn.cdu.basics.exception.BusinessException;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
//  import io.swagger.v3.oas.annotations.Parameter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Parameter;

import java.util.List;
import java.util.Map;

/**
 * 医生工作台控制器
 */
@RestController
@RequestMapping("/zwz/doctorWorkbench")
@Tag(name = "医生工作台")
public class DoctorWorkbenchController {
    private static final Logger log = LoggerFactory.getLogger(DoctorWorkbenchController.class);

    @Autowired
    private IDoctorWorkbenchService doctorWorkbenchService;

    @GetMapping("/info")
    @Operation(summary = "获取医生信息")
    public Result<Map<String, Object>> getDoctorInfo(
            @Parameter(description = "用户ID", required = true) @RequestParam String userId) {
        try {
            Map<String, Object> doctorInfo = doctorWorkbenchService.getDoctorInfo(userId);
            return new ResultUtil<Map<String, Object>>().setData(doctorInfo);
        } catch (BusinessException e) {
            log.error("获取医生信息失败: userId={}, error={}", userId, e.getMessage());
            return new ResultUtil<Map<String, Object>>().setErrorMsg(e.getMessage());
        } catch (Exception e) {
            log.error("获取医生信息发生系统错误: userId={}", userId, e);
            return new ResultUtil<Map<String, Object>>().setErrorMsg("系统错误，请稍后重试");
        }
    }

    @GetMapping("/patients")
    @Operation(summary = "获取患者列表")
    public Result<List<Map<String, Object>>> getPatientList(
            @Parameter(description = "用户ID", required = true) @RequestParam String userId,
            @Parameter(description = "状态：WAITING-待诊，IN_PROGRESS-诊疗中，COMPLETED-已诊", required = true) @RequestParam String status,
            @Parameter(description = "页码", required = false) @RequestParam(required = false) Integer pageNumber,
            @Parameter(description = "每页数量", required = false) @RequestParam(required = false) Integer pageSize,
            @Parameter(description = "搜索关键词", required = false) @RequestParam(required = false) String searchKey) {
        try {
            // 转换状态值
            Integer statusCode = convertStatus(status);

            // 如果提供了分页参数，使用分页查询
            if (pageNumber != null && pageSize != null) {
                Map<String, Object> result = doctorWorkbenchService.getPatientList(userId, pageNumber, pageSize, searchKey);
                return new ResultUtil<List<Map<String, Object>>>().setData((List<Map<String, Object>>) result.get("records"));
            } else {
                List<Map<String, Object>> patients = doctorWorkbenchService.getPatientsByStatus(userId, statusCode);
                return new ResultUtil<List<Map<String, Object>>>().setData(patients);
            }
        } catch (BusinessException e) {
            log.error("获取患者列表失败: userId={}, status={}, error={}", userId, status, e.getMessage());
            return new ResultUtil<List<Map<String, Object>>>().setErrorMsg(e.getMessage());
        } catch (Exception e) {
            log.error("获取患者列表发生系统错误: userId={}, status={}", userId, status, e);
            return new ResultUtil<List<Map<String, Object>>>().setErrorMsg("系统错误，请稍后重试");
        }
    }

    @GetMapping("/patients/list")
    @Operation(summary = "分页获取当前医生的患者列表")
    public Result<Map<String, Object>> getPatientList(
            @RequestParam String userId,
            @RequestParam(required = false, defaultValue = "1") Integer pageNumber,
            @RequestParam(required = false, defaultValue = "20") Integer pageSize,
            @RequestParam(required = false) String searchKey) {
        try {
            Map<String, Object> result = doctorWorkbenchService.getPatientList(userId, pageNumber, pageSize, searchKey);
            return new ResultUtil<Map<String, Object>>().setData(result);
        } catch (Exception e) {
            log.error("获取患者列表失败", e);
            return new ResultUtil<Map<String, Object>>().setErrorMsg("获取患者列表失败：" + e.getMessage());
        }
    }

    @GetMapping("/patients/waiting")
    @Operation(summary = "获取待诊患者列表")
    public Result<List<Map<String, Object>>> getWaitingPatients(
            @Parameter(description = "用户ID", required = true) @RequestParam String userId) {
        try {
            List<Map<String, Object>> patients = doctorWorkbenchService.getWaitingPatients(userId);
            return new ResultUtil<List<Map<String, Object>>>().setData(patients);
        } catch (BusinessException e) {
            log.error("获取待诊患者列表失败: userId={}, error={}", userId, e.getMessage());
            return new ResultUtil<List<Map<String, Object>>>().setErrorMsg(e.getMessage());
        } catch (Exception e) {
            log.error("获取待诊患者列表发生系统错误: userId={}", userId, e);
            return new ResultUtil<List<Map<String, Object>>>().setErrorMsg("系统错误，请稍后重试");
        }
    }

    @GetMapping("/patients/in-progress")
    @Operation(summary = "获取诊疗中患者列表")
    public Result<List<Map<String, Object>>> getInProgressPatients(
            @Parameter(description = "用户ID", required = true) @RequestParam String userId) {
        try {
            List<Map<String, Object>> patients = doctorWorkbenchService.getInProgressPatients(userId);
            return new ResultUtil<List<Map<String, Object>>>().setData(patients);
        } catch (BusinessException e) {
            log.error("获取诊疗中患者列表失败: userId={}, error={}", userId, e.getMessage());
            return new ResultUtil<List<Map<String, Object>>>().setErrorMsg(e.getMessage());
        } catch (Exception e) {
            log.error("获取诊疗中患者列表发生系统错误: userId={}", userId, e);
            return new ResultUtil<List<Map<String, Object>>>().setErrorMsg("系统错误，请稍后重试");
        }
    }

    @GetMapping("/patients/completed")
    @Operation(summary = "获取已诊患者列表")
    public Result<List<Map<String, Object>>> getCompletedPatients(
            @Parameter(description = "用户ID", required = true) @RequestParam String userId) {
        try {
            List<Map<String, Object>> patients = doctorWorkbenchService.getCompletedPatients(userId);
            return new ResultUtil<List<Map<String, Object>>>().setData(patients);
        } catch (BusinessException e) {
            log.error("获取已诊患者列表失败: userId={}, error={}", userId, e.getMessage());
            return new ResultUtil<List<Map<String, Object>>>().setErrorMsg(e.getMessage());
        } catch (Exception e) {
            log.error("获取已诊患者列表发生系统错误: userId={}", userId, e);
            return new ResultUtil<List<Map<String, Object>>>().setErrorMsg("系统错误，请稍后重试");
        }
    }

    @PutMapping("/patients/{patientId}/status")
    @Operation(summary = "更新患者状态")
    public Result<Boolean> updatePatientStatus(
            @Parameter(description = "患者ID", required = true) @PathVariable String patientId,
            @Parameter(description = "状态：WAITING-待诊，IN_PROGRESS-诊疗中，COMPLETED-已诊", required = true) @RequestParam String status) {
        try {
            log.info("Updating patient status - patientId: {}, status: {}", patientId, status);
            String convertedStatus = String.valueOf(convertStatus(status));
            log.info("Converted status: {}", convertedStatus);
            boolean result = doctorWorkbenchService.updatePatientStatus(patientId, convertedStatus);
            log.info("Update result: {}", result);
            return new ResultUtil<Boolean>().setData(result);
        } catch (BusinessException e) {
            log.error("更新患者状态失败: patientId={}, status={}, error={}", patientId, status, e.getMessage());
            return new ResultUtil<Boolean>().setErrorMsg(e.getMessage());
        } catch (Exception e) {
            log.error("更新患者状态发生系统错误: patientId={}, status={}", patientId, status, e);
            return new ResultUtil<Boolean>().setErrorMsg("系统错误，请稍后重试");
        }
    }

    @GetMapping("/patients/{patientId}/history")
    @Operation(summary = "获取患者历史记录")
    public Result<List<Map<String, Object>>> getPatientHistory(
            @Parameter(description = "患者ID", required = true) @PathVariable String patientId) {
        try {
            List<Map<String, Object>> history = doctorWorkbenchService.getPatientHistory(patientId);
            return new ResultUtil<List<Map<String, Object>>>().setData(history);
        } catch (BusinessException e) {
            log.error("获取患者历史记录失败: patientId={}, error={}", patientId, e.getMessage());
            return new ResultUtil<List<Map<String, Object>>>().setErrorMsg(e.getMessage());
        } catch (Exception e) {
            log.error("获取患者历史记录发生系统错误: patientId={}", patientId, e);
            return new ResultUtil<List<Map<String, Object>>>().setErrorMsg("系统错误，请稍后重试");
        }
    }

    @GetMapping("/schedules")
    @Operation(summary = "获取医生排班信息")
    public Result<List<Map<String, Object>>> getSchedules(
            @Parameter(description = "用户ID", required = true) @RequestParam String userId,
            @Parameter(description = "开始日期", required = true) @RequestParam String startDate,
            @Parameter(description = "结束日期", required = true) @RequestParam String endDate) {
        try {
            List<Map<String, Object>> schedules = doctorWorkbenchService.getDoctorSchedules(userId, startDate, endDate);
            return new ResultUtil<List<Map<String, Object>>>().setData(schedules);
        } catch (BusinessException e) {
            log.error("获取医生排班信息失败: userId={}, startDate={}, endDate={}, error={}",
                    userId, startDate, endDate, e.getMessage());
            return new ResultUtil<List<Map<String, Object>>>().setErrorMsg(e.getMessage());
        } catch (Exception e) {
            log.error("获取医生排班信息发生系统错误: userId={}, startDate={}, endDate={}",
                    userId, startDate, endDate, e);
            return new ResultUtil<List<Map<String, Object>>>().setErrorMsg("系统错误，请稍后重试");
        }
    }

    /**
     * 转换状态字符串为状态码
     *
     * @param status 状态字符串
     * @return 状态码
     * @throws BusinessException 如果状态值无效
     */
    private Integer convertStatus(String status) throws BusinessException {
        switch (status.toUpperCase()) {
            case "WAITING":
                return 0;
            case "IN_PROGRESS":
                return 1;
            case "COMPLETED":
                return 2;
            default:
                throw new BusinessException("无效的状态值: " + status);
        }
    }
} 